﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CommunicationModule;

namespace Demo
{
    public partial class TCPSetting : Form
    {
        public TCPSetting()
        {
            InitializeComponent();
            this.txb_IP.Text = "127.0.0.1";
            this.txb_Com.Text = "9000";
            this.list_Client.MultiColumn = false;
            TCPService.Instance.SendMessage += AddInfo;
            TCPService.Instance.AddSocketList += Instance_AddSocketList;
            this.FormClosed += TCPSetting_FormClosed;
        }

        private void Instance_AddSocketList(Dictionary<string, System.Net.Sockets.Socket> obj)
        {
            this.Invoke(new Action(() =>
            {
                list_Client.Items.Clear();
                foreach (string item in obj.Keys)
                {
                    list_Client.Items.Add(item);
                }
            }));
        }

        private void TCPSetting_FormClosed(object sender, FormClosedEventArgs e)
        {
            TCPService.Instance.Close();
        }

        private void AddInfo(string obj)
        {
            if (this.IsHandleCreated)
            {
                this.Invoke(new Action(() =>
                {
                    list_Rec.Items.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss\t" + obj));
                }));
            }
           
        }

        private void btn_StartService_Click(object sender, EventArgs e)
        {
            if (btn_StartService.Text == "启 动 服 务")
            {
                TCPService.Instance.StartService(this.txb_IP.Text, int.Parse(this.txb_Com.Text));
                btn_StartService.Text = "关 闭 服 务";
            }
            else
            {
                btn_StartService.Text = "启 动 服 务";
                TCPService.Instance.Close();
            }

        }

        private void btn_SendMessage_Click(object sender, EventArgs e)
        {
            try
            {
                string tempIP = this.list_Client.SelectedItem.ToString();
                TCPService.Instance.Send(this.txb_SendMessage.Text, tempIP);
            }
            catch
            {
                MessageBox.Show("请选择需要发送的设备！");
            }
            
        }
    }
}
